package com.itheima.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.itheima.model.mongo.UserLocation;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metric;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class UserLocationApiImpl implements UserLocationApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public Boolean saveUpdate(Long userId, Double longitude, Double latitude, String address) {
        try {
            UserLocation userLocation = mongoTemplate.findOne(Query.query(Criteria.where("userId").is(userId)), UserLocation.class);
            if (userLocation==null){
                //添加
                userLocation=new UserLocation();
                userLocation.setUserId(userId);
                userLocation.setAddress(address);
                userLocation.setLocation(new GeoJsonPoint(longitude,latitude));
                userLocation.setCreated(System.currentTimeMillis());
                userLocation.setUpdated(System.currentTimeMillis());
                userLocation.setLastUpdated(System.currentTimeMillis());
            }else {
                //更新
                Update update = Update.update("location", new GeoJsonPoint(longitude, latitude))
                        .set("address",address)
                        .set("lastUpdated",userLocation.getUpdated())
                        .set("updated",System.currentTimeMillis());
                mongoTemplate.updateFirst(Query.query(Criteria.where("userId").is(userId)),update,UserLocation.class);
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public List<Long> queryByLocation(Long userId, String distance) {
        UserLocation userLocation = mongoTemplate.findOne(Query.query(Criteria.where("userId").is(userId)), UserLocation.class);
        if(userLocation==null){
            return null;
        }
        //圆心
        GeoJsonPoint point =userLocation.getLocation();
        //半径
        Distance distance1 = new Distance(Double.valueOf(distance) / 1000, Metrics.KILOMETERS);
        //圆
        Circle circle = new Circle(point, distance1);
        //查询条件
        Query query = Query.query(Criteria.where("location").withinSphere(circle));
        List<UserLocation> userLocations = mongoTemplate.find(query, UserLocation.class);
        return CollUtil.getFieldValues(userLocations,"userId",Long.class);


    }
}
